package sk.stu.fei.tomsteam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

public class SimpleSnmpClient {

	private String address;

	private Snmp snmp;


	public SimpleSnmpClient(String address) {
		super();
		this.address = address;
		try {
			start();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void listenForTrap() {
		CommandResponder trapPrinter = new CommandResponder() {
		     public synchronized void processPdu(CommandResponderEvent e) {
		       PDU command = e.getPDU();
		       if (command != null) {
		         System.out.println(command.toString());
		       }
		       else {
		    	   System.out.println("command == null");
		       }
		     }
		   };
		   
		try {
			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping(
					new UdpAddress("0.0.0.0/162"));
			Snmp snmp = new Snmp(transport);
			snmp.addCommandResponder(trapPrinter);
			snmp.listen();
			Thread.sleep(120000);
			snmp.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// Since snmp4j relies on asynch req/resp we need a listener
	// for responses which should be closed
	public void stop() throws IOException {
		snmp.close();
	}

	private void start() throws IOException {
		snmp = new Snmp(new DefaultUdpTransportMapping());
		snmp.listen();
	}
	
	public String processResponse(OID oid, String community) throws IOException {
		Address targetAddress = GenericAddress.parse(address);
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(targetAddress);
		target.setRetries(2);
		target.setTimeout(500);
		target.setVersion(SnmpConstants.version2c);
		//target.setVersion(SnmpConstants.version1);
		
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(oid));
		ResponseEvent response = snmp.send(pdu, target);
		
		if (response.getResponse() == null) {
			return "TimedOut";
		}
		else {
			return response.getResponse().get(0).getVariable().toString();
		}
	}
}
	